package chapter10_2_cyclic;

import lombok.SneakyThrows;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Summerday
 */
public class CycleBarrierTest1 {

    private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(
            2, // 计数器的初始值
            new Runnable() { // 计数器值为0时需要执行的任务
                @Override
                public void run () {
                    System.out.println(Thread.currentThread() + " task merge result");
                }
            });

    public static void main (String[] args) {
        // 创建大小为2的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.submit(new Runnable() {
            @SneakyThrows
            @Override
            public void run () {
                Thread thread = Thread.currentThread();
                System.out.println(thread + " task A");
                System.out.println(thread + " enter in barrier");
                // 计数器 - 1, 不为0 则阻塞
                cyclicBarrier.await();
                System.out.println(thread + " enter out barrier");
            }
        });

        executorService.submit(new Runnable() {
            @SneakyThrows
            @Override
            public void run () {
                Thread thread = Thread.currentThread();
                System.out.println(thread + " task B");
                System.out.println(thread + " enter in barrier");
                // 计数器为0 则执行 构造器中的任务,执行完毕退出屏障点, 并且唤醒被阻塞的另一个线程
                cyclicBarrier.await();
                System.out.println(thread + " enter out barrier");
            }
        });

        executorService.shutdown();
    }
}
